package com.an.blog.third.auth;

import com.an.blog.third.auth.cache.AuthStateRedisCache;
import com.an.common.exception.blog.BlogException;
import com.an.common.utils.spring.SpringUtils;
import com.xkcoding.justauth.autoconfigure.JustAuthProperties;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.AuthGiteeScope;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthQqRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthScopeUtils;

import java.util.Map;

/**
 * 身份验证请求跑龙套
 *
 * @author: Ann
 * @createDate: 2023/05/31 08:34:28
 * @version: 1.0.0
 */
public class AuthRequestUtils {

    private static final AuthStateRedisCache STATE_REDIS_CACHE = SpringUtils.getBean(AuthStateRedisCache.class);

    private static final JustAuthProperties JUST_AUTH_PROPERTIES = SpringUtils.getBean(JustAuthProperties.class);

    /**
     * 获得身份验证请求
     *
     * @param source 源
     * @return {@link AuthRequest }
     * @author: Ann
     * @createDate: 2023/05/31 08:23:40
     * @version: 1.0.0
     */
    public static AuthRequest getAuthRequest(String source) {
        AuthRequest authRequest = null;
        switch (source.toLowerCase()) {
            case "gitee":
                Map<String, AuthConfig> type = JUST_AUTH_PROPERTIES.getType();
                AuthConfig gitee = type.get("GITEE");
                authRequest = new AuthGiteeRequest(AuthConfig.builder()
                    .clientId(gitee.getClientId())
                    .clientSecret(gitee.getClientSecret())
                    .redirectUri(gitee.getRedirectUri())
                    .scopes(AuthScopeUtils.getScopes(AuthGiteeScope.USER_INFO))
                    .build(), STATE_REDIS_CACHE);
                break;
            case "qq":
                authRequest = new AuthQqRequest(AuthConfig.builder()
                    .clientId("")
                    .clientSecret("")
                    .redirectUri("http://127.0.0.1:8988/blog-web/oauth/callback/qq")
                    .build());
                break;
            default:
                break;
        }
        if (null == authRequest) {
            throw new BlogException("未获取到有效的Auth配置");
        }
        return authRequest;
    }
}
